package com.nexgo.payment.trans.operator.add;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.aop.annotation.RunOnMainThread;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.OperatorInfo;
import com.nexgo.payment.util.EncryptUtils;
import com.nexgo.payment.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 添加操作员实现
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年09月20日
 */
public class OperatorAddPresenter implements OperatorAddContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(OperatorAddPresenter.class.getSimpleName());

    private OperatorAddContract.View mView;
    private DataSource mRepository;

    public OperatorAddPresenter(@NonNull OperatorAddContract.View view, @NonNull DataSource repository) {
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        mView.setPresenter(this);
    }

    @Override
    public void start() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void addOperator(String operatorNo, String password) {
        if (TextUtils.isEmpty(operatorNo)) {
            postMainThread(() -> mView.showTips(App.sContext.getString(R.string.input_operator)));
            return;
        }
        operatorNo = StringUtils.leftPad(operatorNo, 2, '0');
        if (TextUtils.isEmpty(password)) {
            postMainThread(() -> mView.showTips(App.sContext.getString(R.string.input_operator_password)));
            return;
        }
        OperatorInfo info = mRepository.getOperator(operatorNo);
        if (info != null) {
            postMainThread(() -> mView.showTips(App.sContext.getString(R.string.this_operator_is_exist)));
            return;
        }
        info = new OperatorInfo();
        info.setOperatorNo(operatorNo);
        info.setPassword(EncryptUtils.encryptSHA256ToString(password));
        mRepository.saveOperator(info);
        postMainThread(() -> mView.showTips(App.sContext.getString(R.string.add_success)));
        postMainThread(() -> mView.showSuccess());
    }

    @RunOnMainThread
    private void postMainThread(Runnable runnable) {
        runnable.run();
    }
}
